﻿using System;
using System.Windows.Forms;
using TimeTable.Domain.DataAccess;
using TimeTable.Domain.Entity;

namespace TimeTable.AddForms
{
    public partial class NewTeacherForm : Form
    {
        public NewTeacherForm()
        {
            InitializeComponent();

            chair.DataSource = DataAccessConnection.Instance.GetDivisionsByType(DivisionType.Chair);
        }

        private void CancelButtonClick(object sender, EventArgs e)
        {
            Close();
        }

        private void OKButtonClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(lastName.Text)) throw new Exception("Last Name can not be empty!");
                if (string.IsNullOrEmpty(firstName.Text)) throw new Exception("First Name can not be empty!");
                if (string.IsNullOrEmpty(patronymic.Text)) throw new Exception("Patronymic can not be empty!");
                if (string.IsNullOrEmpty(pasSeries.Text)) throw new Exception("Passport series can not be empty!");
                if (string.IsNullOrEmpty(pasNumber.Text)) throw new Exception("Passport number can not be empty!");
                if (string.IsNullOrEmpty(address.Text)) throw new Exception("Address can not be empty!");

                var division = chair.SelectedItem as Division;
                if (division == null) throw new Exception("Please select chair!");

                var teacher = new Teacher
                {
                    LastName = lastName.Text,
                    FirstName = firstName.Text,
                    Patronymic = patronymic.Text,
                    PassportSeries = int.Parse(pasSeries.Text),
                    PassportNumber = int.Parse(pasNumber.Text),
                    Address = address.Text,
                    Division = division
                };

                if (DataAccessConnection.Instance.TeacherExists(teacher))
                {
                    MessageBox.Show("Teacher already exists!");
                }
                else
                {
                    DataAccessConnection.Instance.AddTeacher(teacher);

                    MessageBox.Show("Teacher successfully added!");

                    Close();
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message, "Error");
            }
        }
    }
}
